package com.laikan.library.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

public final class SPUtil {

    private static SharedPreferences saveInfo;
    private static SharedPreferences.Editor saveEditor;
    private static SPUtil instance;

    private SPUtil() {
    }

    public static SPUtil getInstance() {
        if (instance == null) {
            synchronized (SPUtil.class) {
                instance = new SPUtil();
            }
        }
        return instance;
    }

    // --------- string ----------
    public static boolean putString(String key, String value) {
        saveEditor.putString(key, value);
        return saveEditor.commit();
    }

    public static String getString(String key, String defaultValue) {
        return saveInfo.getString(key, defaultValue);
    }

    // --------- float ----------
    public static boolean putFloat(String key, Float value) {
        saveEditor.putFloat(key, value);
        return saveEditor.commit();
    }

    public static Float getFloat(String key, Float defaultValue) {
        return saveInfo.getFloat(key, defaultValue);
    }

    // --------- boolean ----------
    public static boolean putBoolean(String key, boolean value) {
        saveEditor.putBoolean(key, value);
        return saveEditor.commit();
    }

    public static boolean getBoolean(String key, boolean defaultValue) {
        return saveInfo.getBoolean(key, defaultValue);
    }

    // ---------- int ---------
    public static boolean putInt(String key, int value) {
        saveEditor.putInt(key, value);
        return saveEditor.commit();
    }

    public static int getInt(String key, int defaultValue) {
        return saveInfo.getInt(key, defaultValue);
    }

    // ---------- long ----------
    public static boolean putLong(String key, long value) {
        saveEditor.putLong(key, value);
        return saveEditor.commit();
    }

    public static long getLong(String key, long defaultValue) {
        return saveInfo.getLong(key, defaultValue);
    }

    public void init(Context context, String name) {
        if (saveInfo == null) {
            if (!TextUtils.isEmpty(name)) {
                saveInfo = context.getSharedPreferences(name, Context.MODE_PRIVATE);
            }
            saveEditor = saveInfo.edit();
        }
    }

    /**
     * 删除全部数据
     *
     * @return
     */
    public boolean clearAllItem() {
        saveEditor.clear();
        return saveEditor.commit();
    }
}
